<template></template>

<script setup lang="ts">
import * as L from 'leaflet'
import type { IPixelLayerStyleOptions } from '@quickearth/core'
import {
  GridDataGLFillMode,
  MemoryWindDataProvider,
  QEGridDataProvider,
  getBinary,
  resourceService,
  getText,
  MicapsDiamond4GridDataProvider
} from '@quickearth/core'
const centerApi = import.meta.env.VITE_BASE_URL
import { LGridLabelLayer, LPixelLayer } from '@quickearth/leaflet'
import { usePredictionStore } from '@/pages/conventional-fine-forecasting/store/store'
import apiList from '@/pages/conventional-fine-forecasting/api/api'
const predictionStore = usePredictionStore()

const gdskjcCurrentActive = computed(() => predictionStore.gdskjcCurrentActive)
const componentsVisible = computed(() => predictionStore.componentsVisible)
const gdskjcDataList = computed(() => predictionStore.gdskjcDataList)
const timerInterval = computed(() => predictionStore.timerInterval)
const timerIndex = computed(() => predictionStore.timerIndex)
const rowData = ref([])
const baseMap = inject('baseMap')
let windLayer, layer, lPixelLayer
const layers = L.layerGroup().addTo(toRaw(baseMap.value))
async function updateGridLayer(type, styleType) {
  // predictionStore.mapLoading = true
  await resourceService.loadResourceFromConfigPath(
    'demos/styles/demo.config.json'
  )
  layers.clearLayers()
  if (styleType === 'wind') {
    let newList =
      rowData.value[
        timerIndex.value
          ? timerIndex.value == 0
            ? 0
            : timerIndex.value - 1
          : 0
      ].url.split(',')
    const uBuffer = await getBinary(centerApi + newList[0]) // uwind
    const vBuffer = await getBinary(centerApi + newList[1]) // vwind
    const uProvider = new QEGridDataProvider(uBuffer[0])
    const vProvider = new QEGridDataProvider(vBuffer[0])
    const provider = new MemoryWindDataProvider(uProvider, vProvider, {
      lazyCalc: false,
      isUV: true
    })
    windLayer = new LGridLabelLayer({
      name: '风向风速',
      debugShowPerformance: true,
      accurateYDelta: true //对于范围较大的数据，设置后会根据当前点所在的实际纬度计算y值在径向上的间隔变化，会稍微增加渲染时间。
    })
      .setDrawOptions({
        image: {
          data: 'image-wind#res',
          angle: '#degree2arc|1',
          color: 'color-wind#res'
        }
      })
      .setDataSource(provider)
    layers.addLayer(windLayer)
    const Buffer = await getBinary(centerApi + newList[2])
    const providerNew = new QEGridDataProvider(Buffer[0])
    layer = new LPixelLayer()
    const style: IPixelLayerStyleOptions = {
      fillColor: `color-wind-new#res`,
      globalOpacity: 0.9,
      fillMode: GridDataGLFillMode.pixel1
    }
    layer.setDataSource(providerNew).setDrawOptions(style)
    layer.addTo(toRaw(baseMap.value))
    layers.addLayer(layer)
    predictionStore.mapLoading = false
  } else {
    const Buffer = await getBinary(
      centerApi +
        rowData.value[
          timerIndex.value
            ? timerIndex.value == 0
              ? 0
              : timerIndex.value - 1
            : 0
        ].url
    )
    const provider = new QEGridDataProvider(Buffer[0])
    lPixelLayer = new LPixelLayer()
    const style: IPixelLayerStyleOptions = {
      fillColor: `color-${styleType}#res`,
      globalOpacity: 0.9,
      fillMode: GridDataGLFillMode.pixel1
    }
    lPixelLayer.setDataSource(provider).setDrawOptions(style)
    layers.addLayer(lPixelLayer)
    predictionStore.mapLoading = false
  }
}
const handleShowLayer = type => {
  const currentSelect = predictionStore.gdskjcOptions.find(
    i => i.value === gdskjcCurrentActive.value
  )
  if (currentSelect) {
    updateGridLayer(type, currentSelect.legendStyle)
  }
}
useEventBus('handleShowGridPointMonitoringLayer').on(handleShowLayer)
const initData = () => {
  apiList
    .getTimerShaftAndchoroplethicMap({
      intervalHour: timerInterval.value ? timerInterval.value : 1,
      elementCode: predictionStore.gdskjcCurrentActive
    })
    .then(res => {
      rowData.value = res.data.list
      predictionStore.gdskjcAllDataList = res.data.list
    })
}
watch(
  () => timerInterval.value,
  newV => {
    initData()
    setTimeout(() => {
      handleShowLayer()
    }, 500)
  }
)
watch(
  () => timerIndex.value,
  newV => {
    handleShowLayer()
  }
)
watch(
  () => gdskjcCurrentActive.value,
  val => {
    if (val !== 'none') {
      if (layers) {
        layers.clearLayers()
      }
      initData()
      setTimeout(() => {
        handleShowLayer(val)
      }, 500)
    } else {
      layers.clearLayers()
    }
  },
  {
    deep: true
  }
)
watch(
  () => componentsVisible.value.fgt,
  val => {
    if (val !== 'none') {
      if (layers) {
        layers.clearLayers()
      }
      setTimeout(() => {
        handleShowLayer(val)
      }, 500)
    } else {
      layers.clearLayers()
    }
  },
  {
    deep: true
  }
)
onMounted(() => {
  initData()
  setTimeout(() => {
    if (gdskjcCurrentActive.value !== 'none') {
      handleShowLayer(gdskjcCurrentActive.value)
    }
  }, 100)
})
onUnmounted(() => {
  layers.clearLayers()
})
</script>

<style scoped lang="scss"></style>
